import {
	BASE_URL,
	AccessKey,
	SecretKey,
	generateRandomNumber,
	convertDataToString,
	createSignature
} from '@/common/baseUrl.js'

import { open_from } from "@/request/open_from.js";


// const baseUrl = "http://api-web.kdxgs.com/api/";

// // 从配置或环境变量中获取密钥信息
// const accessKey = 'BVKIypntExsraSwok5MNmMvW6J'; 
// const secretKey = 'LvRg4dJax8z0m36Ieodv1ynX7bqhJ5FWEQBM4K'; 
const methodArr = ['POST', 'PUT','DELETE'] // body参数需要生成签名

export default function request(url, params = {}) {
	
    return new Promise((resolve, reject) => {
        //是否展示loading
        const showLoading = params.showLoading === undefined ? true : params.showLoading;
        // 先展示一下等待的弹窗
        if (showLoading) {
            uni.showLoading({
                title: '加载中',
            })
        }
        // let ApiCpsKey = uni.getStorage、Sync('ApiCpsKey');
        let headerDate = {
        	accessKey: AccessKey,
        	nonceStr: generateRandomNumber(),
        	secretKey: SecretKey,
        	data : methodArr.includes(params.method) ? params.data : {},
        	timestamp: Math.floor(new Date().getTime() / 1000),
        }
		// let headerDate = {
		// 	accessKey: AccessKey,
		// 	nonceStr: "5K8264ILTKCH16CQ2502SI8ZNMTM67VS",
		// 	secretKey: SecretKey,
		// 	data : {"id" : '1', "name" : "名称"},
		// 	timestamp: '1735787372',
		// }
		
        let signature = createSignature(convertDataToString(headerDate))
        // 生成签名相关的请求头
        // const signatureHeaders = generateSignatureHeaders(params.data || {}, accessKey, secretKey);
        
        let header = {
            'Authorization': 'Bearer' + uni.getStorageSync('token'),
            // 'Api-Promotion-Link-Id':"1",
            // 'Api-Promotion-Keyword-Id': "1",
			"api-mini-program-id": "1", //小程序id
			"api-access-key": headerDate.accessKey, //公钥
			"api-timestamp": headerDate.timestamp, //时间戳
			"api-nonce-str": headerDate.nonceStr, //随机数不超过32位
			"api-signature": signature, //签名
            "Content-Type": "application/json",
        };
        
        uni.request({
            url: BASE_URL + url,
            data: params.data,
            header: header || {},
            timeout: 60000,
            method: params.method || "GET",
            dataType: "json",
            success: (res) => {
                uni.hideLoading();
                resolve(res.data);
            },
            fail: (err) => {
                uni.hideLoading();
                uni.showToast({
                    title: "请求失败",
                    icon: "error"
                });
                reject(err);
            }
        });
    });
}